package jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

public class Register {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        System.out.println("请输入用户名");
        String username = scanner.nextLine();
        System.out.println("请输入密码");
        String password = scanner.nextLine();
        System.out.println("请输入昵称");
        String nickname = scanner.nextLine();
        System.out.println("请输入年龄");
        int age = scanner.nextInt();

        try (Connection connection = DBUtil.getConnection()){
            String sql = "SELECT username FROM userinfo WHERE username=? AND password=?";
            PreparedStatement ps = connection.prepareStatement(sql);
            //设置 ? 的值
            ps.setString(1, username);
            ps.setString(2, password);
            //执行SQL语句
            ResultSet rs = ps.executeQuery();
            if (rs.next()){
                    System.out.println("用户名已被占用");
            }else {
            String sql2 = "INSERT INTO userinfo(username,password,nickname,age) VALUES(?,?,?,?)";
            PreparedStatement ps2 = connection.prepareStatement(sql2);
            ps2.setString(1, username);
            ps2.setString(2, password);
            ps2.setString(3, nickname);
            ps2.setInt(4, age);
            ps2.executeUpdate();
            System.out.println("恭喜你,注册成功");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}
